package com.mvc.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

/**
 * 反射工具类
 * @author feng
 *
 */
public class ReflectUtil {
	
	public static Object getClassByName(final String className){
		Class<?> clzz = null;
		try {
			clzz = Class.forName(className);
			return clzz.newInstance();
		} catch(Exception e){
			e.printStackTrace();
		}
		return clzz;
		
	}
	
	/**
	 * 反射调用方法
	 * @param request
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static Object invoke(Request request,HttpServletRequest req) throws Exception{
		Object object = getClassByName(request.getClassName());
		RequestParam param = null;
		Method method = null;
		if(request.getParameterTypes() != null && request.getParameterTypes().length > 0){
			Class<?> paramClazz = request.getParameterTypes()[0]; //只有一个RequestParam 对象的参数,由于java 无法获取参数名称,这里统一用一个类来接收
			param = (RequestParam) paramClazz.newInstance();
			Field [] fields = paramClazz.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true); //设置private 可以访问
				field.set(param, req.getParameter(field.getName())); //设置属性值
				field.setAccessible(false);
			}
			method = object.getClass().getMethod(request.getRequestMothod(),request.getParameterTypes());
			return method.invoke(object,param);
		}else{
			method = object.getClass().getMethod(request.getRequestMothod());
			return method.invoke(object);
		}
		
	}

}
